package com.ys.modules.system.controller;

import com.ys.common.result.Result;
import com.ys.common.util.JwtUtil;
import com.ys.modules.system.entity.User;
import com.ys.modules.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(tags = "认证管理")
@RestController
@RequestMapping("/api")
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @ApiOperation("用户登录")
    @ApiResponses({
        @ApiResponse(code = 200, message = "登录成功，返回token", response = String.class),
        @ApiResponse(code = 400, message = "用户名或密码错误")
    })
    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        if (username == null || password == null) {
            return Result.fail("用户名和密码不能为空");
        }
        
        User user = userService.findByUsername(username);
        if (user == null) {
            return Result.fail("用户名或密码错误");
        }
        boolean passwordMatches = passwordEncoder.matches(password, user.getPassword());

        if (!passwordMatches) {
            return Result.fail("用户名或密码错误");
        }
        
        String token = jwtUtil.generateToken(username);
        return Result.success(token);
    }

    @ApiOperation("获取当前用户信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "返回用户信息", response = User.class),
        @ApiResponse(code = 401, message = "未认证")
    })
    @GetMapping("/me")
    public Result<?> me(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            return Result.fail("未认证");
        }
        String token = header.substring(7);
        String username = jwtUtil.getUsername(token);
        User user = userService.findByUsername(username);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        user.setPassword(null);
        return Result.success(user);
    }
} 